package com.m1.tzolkin.model.util.zone;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import com.m1.tzolkin.model.exceptions.StepMoveException;

public class StepsZone<P> implements IStepsZone<P> {
	
	// ATTRIBUTS
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1391730688210659679L;
	private final int steps;
	private final Map<P, Integer> players;
	
	// CONSTRUCTEUR
	
	public StepsZone(int n) {
		if (n <= 0) {
			throw new IllegalArgumentException();
		}
		steps = n;
		players = new HashMap<P, Integer>();
	}
	
	// REQUETES

	@Override
	public Collection<P> getKeys() {
		return players.keySet();
	}

	@Override
	public Integer getStep(P p) {
		if (p == null) {
			throw new IllegalArgumentException();
		}
		return players.get(p);
	}

	@Override
	public int getStepsNb() {
		return steps;
	}
	
	// COMMANDES

	@Override
	public void addKey(P p) {
		addKey(p, 0);
	}

	@Override
	public void addKey(P p, int i) {
		if (p == null || players.keySet().contains(p) || i < 0 || i >= steps) {
			throw new IllegalArgumentException();
		}
		if (players.keySet().contains(p)) {
			throw new IllegalStateException();
		}
		players.put(p, i);
	}

	@Override
	public void up(P p) throws StepMoveException {
		if (p == null || !players.keySet().contains(p)) {
			throw new IllegalArgumentException();
		}
		int step = players.get(p) + 1;
		if (step >= steps) {
			throw new StepMoveException();
		}
		players.put(p, step);
	}

	@Override
	public void down(P p) throws StepMoveException {
		if (p == null || !players.keySet().contains(p)) {
			throw new IllegalArgumentException();
		}
		int step = players.get(p) - 1;
		if (step < 0) {
			throw new StepMoveException();
		}
		players.put(p, step);
	}

}
